package org.wxd.common.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

/**
 * Created by wangxd on 2017/2/8.
 */
public final class JDBCUtil {


    public static Connection build(String driver,String url,String username,String password) throws Exception {
        Class.forName(driver);
        return DriverManager.getConnection(url,username,password);
    }

    public static void close(Connection connection,Statement st,ResultSet rs) throws Exception {
        try {
            closeResultSet(rs);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                closeStatement(st);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                closeConnection(connection);
            }
        }
    }

    public static void closeConnection(Connection connection) throws Exception {
        if (connection != null && !connection.isClosed()) {
            connection.close();
            connection = null;
        }
    }

    public static void closeResultSet(ResultSet rs) throws Exception {
        if (rs != null) {
            rs.close();
            rs = null;
        }
    }

    public static void closeStatement(Statement st) throws Exception {
        if (st != null) {
            st.close();
            st = null;
        }
    }

}
